package leetcode.editor.cn.q1_300.q50;

/**
 * @author qidi
 * @date 2021-12-21 14:07:49
 */
class Q0082_RemoveDuplicatesFromSortedListIi {

    /**
     * Definition for singly-linked list.
     */
    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if (head == null) return null;

            ListNode newH = null;
            ListNode tail = null;
            ListNode slow = head;
            ListNode fast = head.next;
            if (fast == null) return head;

            int num = 1;
            while (fast != null) {
                if (slow.val != fast.val) {
                    if (num == 1) {
                        if (newH == null) {
                            newH = slow;
                            tail = newH;
                        } else {
                            tail.next = slow;
                            tail = tail.next;
                        }
                    } else {
                        num = 1;
                    }
                    slow = fast;
                    fast = fast.next;
                } else {
                    num++;
                    fast = fast.next;
                }
            }

            if (newH != null) tail.next = null;

            if (num == 1) {
                if (newH == null) {
                    newH = slow;
                } else {
                    tail.next = slow;
                }
            }

            return newH;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

    public static void main(String[] args) {
        Solution solution = new Q0082_RemoveDuplicatesFromSortedListIi().new Solution();
        ListNode node = new ListNode(1);
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(4);
        ListNode node6 = new ListNode(5);

        node.next = node1;
//        node1.next = node2;
//        node2.next = node3;
//        node3.next = node4;
//        node4.next = node5;
//        node5.next = node6;

        solution.deleteDuplicates(node);
    }
}